class Category < ActiveRecord::Base
  has_many :categoryImages, :dependent => true
  has_many :images, :through => :categoryImages
  has_many :categories
  belongs_to :category

  validates_presence_of :code
  validates_presence_of :image_id
  validates_uniqueness_of :code
  
  def thumburl
    @thumbImage = Image.find_by_id(image_id)
    "http://www.henrywagner.org" + @thumbImage.directory + "thumb/" + @thumbImage.filename
  end
  
  def randomImage
    @images = Image.find_by_sql(["SELECT * from images i, category_images ci WHERE i.id = ci.image_id AND ci.category_id = ? ORDER BY RAND() LIMIT 1", id])
    @images[0]
  end
end
